package com.cyd.util;

import java.io.File;

import android.content.Context;
import android.widget.ImageView;

import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.cache.disc.naming.HashCodeFileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.UsingFreqLimitedMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
import com.nostra13.universalimageloader.utils.StorageUtils;

public class ImageLoaderUtil {
	private File cacheDir;
	private ImageLoaderConfiguration config;
	private static Context context;
	private ImageLoader imageLoader;
	private DisplayImageOptions options;

	public static ImageLoaderUtil getInstance(Context context) {
		ImageLoaderUtil.context = context;
		return new ImageLoaderUtil();
	}

	private ImageLoaderUtil() {
		cacheDir = StorageUtils.getOwnCacheDirectory(context, "cache");
		imageLoader = ImageLoader.getInstance();
		initImageLoaderConfiguration();
	}

	private void initImageLoaderConfiguration() {
		// TODO Auto-generated method stub
		config = new ImageLoaderConfiguration.Builder(context)
				.memoryCacheExtraOptions(480, 800)
				.threadPoolSize(3)
				.memoryCache(new UsingFreqLimitedMemoryCache(2 * 1024 * 1024))
				.memoryCacheSize(2 * 1024 * 1024)
				.diskCacheFileCount(110)
				.diskCache(new UnlimitedDiscCache(cacheDir))
				.diskCacheFileNameGenerator(new HashCodeFileNameGenerator())
				.imageDownloader(
						new BaseImageDownloader(context, 15 * 1000, 50 * 1000))
				.build();
		initOptions();
		imageLoader.init(config);
	}

	private void initOptions() {
		// TODO Auto-generated method stub
		options = new DisplayImageOptions.Builder().showImageOnFail(0)
				.showImageOnLoading(0).showImageForEmptyUri(0)
				.cacheInMemory(true).cacheOnDisk(true)
				.resetViewBeforeLoading(true)
				.displayer(new RoundedBitmapDisplayer(20))
				.imageScaleType(ImageScaleType.EXACTLY)
				.displayer(new FadeInBitmapDisplayer(1000)).build();
	}

	public void disPlayImage(String url, ImageView img) {
		imageLoader.displayImage(url, img, options);
	}

}
